package com.wj.config;

import com.wj.entity.UserEntity;
import com.wj.mapper.UserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashSet;

/**
 * @author WangJin
 * @version 1.0
 * @date 2022/2/12 15:04
 */
@Configuration
public class Realm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;


    /**
     * 根据用户角色授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取用户名称
        String username = (String) principals.getPrimaryPrincipal();
        UserEntity dbUser = userMapper.findByUsername(username);
        if (dbUser == null) {
            return null;
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
         //设置权限
        HashSet<String> roles = new HashSet<>();
        String role = dbUser.getRole();
        if (role == null) {
            return null;
        }
        String[] split = role.split(",");
        for (String s : split) {
            roles.add(s);
        }
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }

    /**
     * 验证账号密码
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        if(userName == null){
            return null;
        }
        UserEntity dbUser = userMapper.findByUsername(userName);
        if(dbUser == null){
            return null;
        }

      //使用数据库db的密码验证 用户输入的密码
        SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(dbUser.getUsername(), dbUser.getPassword(), dbUser.getRealname());

            return  authorizationInfo;
    }
}
